﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Circle.Domain.Interface.Service;
using Microsoft.Practices.Unity;
using Circle.Domain.Model;
using System.Security.Principal;

namespace Circle.Service
{

    public class SecurityService :BaseCircleService, ISecurityService
    {

        private static readonly string Security_Service_CacheKey = "Security_Service_CacheKey";
        // Key : UserName which is unique
        private static Dictionary<string, TokenUser> _dictToken;

        
        private  ICacheService _cacheManager { get; set; }


        public SecurityService(ICacheService cacheService)
        {
            _cacheManager = cacheService;
            if (!_cacheManager.Contains(Security_Service_CacheKey))
            {
                _cacheManager.AddOrUpdate(Security_Service_CacheKey, new Dictionary<string, TokenUser>());
            }
            _dictToken = _cacheManager.GetData<Dictionary<string, TokenUser>>(Security_Service_CacheKey);
        }

        public TokenUser ExistingTokenUser(string userName)
        {

            if (_dictToken.ContainsKey(userName)) 
            {
                return _dictToken[userName];
            }

            return null;
        }

        public void AddOrUpdateTokenUser(TokenUser user)
        {

            if (_dictToken.ContainsKey(user.UserName))
            {
                _dictToken[user.UserName] = user;
            }
            else
            {
                _dictToken.Add(user.UserName, user);
            }
        }

        public void AddOrUpdateCurrentTokenUser(TokenUser user)
        {

            if (CurrentUser != null)
            {
                RemoveTokenUser(user.UserName);
            }

            AddOrUpdateTokenUser(user);
            ContextUser = new CirclePrincipal(user);
        }

        public bool VerifyToken(string userName, string token)
        {
            try
            {
                if (_dictToken.ContainsKey(userName))
                {
                    if (_dictToken[userName].Token == token)
                    {
                        return true;
                    }
                }
            }
            catch
            {

            }

            return false;
        }

        public bool VerifyToken(string userName, string token, out TokenUser user)
        {
            try
            {
                if (_dictToken.ContainsKey(userName))
                {
                    if (_dictToken[userName].Token == token)
                    {
                        user = _dictToken[userName];
                        return true;
                    }
                }
            }
            catch
            {

            }

            user = null;
            return false;
        }

        /// <summary>
        /// Verify token item based on current HttpContext User
        /// </summary>
        public bool VerifyToken()
        {
            if (CurrentUser != null)
            {
                return VerifyToken(CurrentUser.UserName, CurrentUser.Token);
            }

            return false;
        }

        /// <summary>
        /// Remove token item based on current HttpContext User
        /// </summary>
        public void RemoveTokenUser()
        {
            if(CurrentUser != null)
            {
               RemoveTokenUser(CurrentUser);
            }
        }

        public void RemoveTokenUser(TokenUser user)
        {
            if (user != null)
            {
                RemoveTokenUser(user.UserName);
            }
        }

        public void RemoveTokenUser(string userName)
        {
            if (_dictToken.ContainsKey(userName))
            {
                _dictToken.Remove(userName);
            }

            if(CurrentUser!= null && CurrentUser.UserName == userName)
            {
                ContextUser = null;
            }
        }

        public void Clear()
        {
            _dictToken.Clear();
        }

        public bool IsCurrentUserValid()
        {
            return (CurrentUser != null) && CurrentUser.IsAuthenticated;
        }

        public TokenUser CurrentUser
        {
            get 
            {
                if (ContextUser != null && ContextUser.Identity != null)
                {
                    if (_dictToken.ContainsKey(ContextUser.Identity.Name)) 
                    {
                        return _dictToken[ContextUser.Identity.Name];
                    }
                }

                return null;
            }
        }

        private IPrincipal ContextUser
        {
            get { return HttpContext.Current.User; }
            set { HttpContext.Current.User = value; }
        }

    }
}